package com.ncmem.up6.store.fastdfs;

import com.ncmem.up6.utils.ConfigReader;
import com.ncmem.up6.utils.FileTool;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class FastDFSTool {

    public FastDFSTool() { }

    public static StorageClient1 client() {

        /*
        DfsConnectPool pool = DfsConnectPool.getPool();
        StorageClient1 sc = pool.checkout(10);
        return sc;

         */
		StorageClient1 storageClient=null;
		 ConfigReader cr = new ConfigReader();

			try {
                try {
                    ClientGlobal.init(cr.readPath("FastDFS"));
                } catch (MyException e) {
                    e.printStackTrace();
                }
                TrackerClient tracker = new TrackerClient();
		        TrackerServer trackerSvr = tracker.getConnection();
		        StorageServer storageSvr = null;
		           //
		        storageClient = new StorageClient1(trackerSvr, storageSvr);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        return storageClient;

    }

    public static void save(StorageClient1 c){
        DfsConnectPool pool = DfsConnectPool.getPool();
        pool.checkin(c);
    }

    public static FileInfo query(String id)
    {
        FileInfo f=null;
        StorageClient1 c = FastDFSTool.client();
        try {
            f = c.query_file_info1(id);
            save(c);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return f;
    }

    public static String upload_test()
    {
        try {
            StorageClient1 cli = FastDFSTool.client();
//	          NameValuePair nvp = new NameValuePair("age", "18");
            NameValuePair nvp [] = new NameValuePair[]{
                    new NameValuePair("age", "18"),
                    new NameValuePair("sex", "male")
            };
            byte[] buf = FileTool.readAllBytes("f:\\test.txt");
            String idSvr = cli.upload_file1(buf, "txt", nvp);

            //System.out.println(fileIds.length);
            //System.out.println("组名：" + fileIds[0]);
            System.out.println(idSvr);
            return idSvr;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String upload(byte[] buf,String ext)
    {
        String file_id="";
        StorageClient1 c = null;
        NameValuePair nvp [] = new NameValuePair[]{};
        try {
            c = client();
            file_id = c.upload_appender_file1(buf, ext, nvp);
            save(c);
        } catch (IOException e) {
            if(null !=c)save(c);
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return file_id;
    }

    public static int write(String fileID, long offset, FileItem block)
    {
        int blockSize = 0;
        try
        {
            blockSize = (int)block.getSize();
            InputStream stream = block.getInputStream();
            byte[] data = new byte[blockSize];
            if(stream.read(data) != blockSize)
            {
                throw new IOException();
            }
            stream.close();

            StorageClient1 cli = FastDFSTool.client();
            cli.append_file1(fileID,data);

        } catch (IOException e) {
            blockSize = 0;
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MyException e) {
            blockSize = 0;
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return blockSize;
    }

    public static boolean write(String fileID,byte[] data)
    {
        try
        {
            StorageClient1 c = FastDFSTool.client();
            c.append_file1(fileID,data);
            save(c);
            return true;
        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MyException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public static byte[] down(String fileID,long offset,long size)
    {
        byte[] buf=new byte[0];
        StorageClient1 c = client();
        try {
            buf = c.download_file1(fileID,offset,size);
            save(c);
        } catch (IOException e) {
            if(c!=null) save(c);
            // TODO Auto-generated catch block
            System.out.println("FastDFSTool.down.error");
            e.printStackTrace();
        } catch (MyException e) {
            // TODO Auto-generated catch block
            System.out.println("FastDFSTool.down.error");
            e.printStackTrace();
        }
        return buf;
    }

    /**
     *
     * @param fileID
     * @param offset
     * @param size
     * @param unit
     * @return
     */
    public static byte[] down_stream(String fileID,long offset,long size,long unit)
    {
        byte[] buf = new byte[(int)size];
        StorageClient1 c = client();
        try {
            long len = 1024;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //大于1KB，必须使用流方式下载
            while(len>0)
            {
                buf = c.download_file1(fileID, offset, len);
                os.write(buf,0,(int)len);
                offset+=len;
                len=(size-offset)>len?len:(size-offset);
            }
            buf = os.toByteArray();
            save(c);
        } catch (IOException e) {
            if(c!=null) save(c);
            // TODO Auto-generated catch block
            System.out.println("FastDFSTool.down.error");
            e.printStackTrace();
        } catch (MyException e) {
            // TODO Auto-generated catch block
            System.out.println("FastDFSTool.down.error");
            e.printStackTrace();
        }
        return buf;
    }
}
